package demo.java.lang.management.jvm;

import demo.java.lang.management.vo.StartupInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;

/**
 * 收集jvm启动时的信息，启动后到下次重启之前不变的信息，如进程ID，启动参数，classpath等
 * @date 16/1/18
 */
public class StartupInfoCollector {

    private static final Logger logger = LoggerFactory.getLogger(StartupInfoCollector.class);

    private RuntimeMXBean Runtime;
    private OperatingSystemMXBean OS;

    public StartupInfoCollector(RuntimeMXBean Runtime, OperatingSystemMXBean OS){
        this.Runtime = Runtime;
        this.OS = OS;
    }

    public StartupInfo collect(){
        StartupInfo startupInfo = new StartupInfo();
        try {
            startupInfo.setPID(JVMUtils.getPID());
            startupInfo.setPort(3306);
            startupInfo.setBootClassPath(Runtime.getBootClassPath());
            startupInfo.setBootClassPathSupported(Runtime.isBootClassPathSupported());
            startupInfo.setClassPath(Runtime.getClassPath());
            startupInfo.setInputArguments(Runtime.getInputArguments().toString());
            startupInfo.setLibraryPath(Runtime.getLibraryPath());
            startupInfo.setManagementSpecVersion(Runtime.getManagementSpecVersion());
            startupInfo.setSystemProperties(System.getProperties().toString());
            startupInfo.setVmName(Runtime.getVmName());
            startupInfo.setVmVendor(Runtime.getVmVendor());
            startupInfo.setVmVersion(Runtime.getVmVersion());
            startupInfo.setStartJvmTime(Runtime.getStartTime());
            startupInfo.setOSVersion(OS.getVersion());
            startupInfo.setOSArch(OS.getArch());
            startupInfo.setOSName(OS.getName());
            startupInfo.setOSAvailableProcessors(OS.getAvailableProcessors());
        }catch (Throwable e){
            logger.error("StartupInfoCollector collect error, {}", e.getMessage());
            return null;
        }

        return startupInfo;
    }
}
